package com.jysz.webcore.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.lang.NullArgumentException;
import org.apache.commons.lang.StringUtils;

/**
 * @author kacarich email:javaengine@outlook.com
 *
 */
public class SshStringUtils {
	
	public static String toGb2312Encode(String s) {
		String r = null;
		if(s != null) {
			try {
				r = URLEncoder.encode(s, "gb2312");
			} catch(Exception e) {
				e.printStackTrace();
				//do nothing
			}
		}
		return r;
	}
	
	public static String toUtf8Encode(String s) {
		String r = null;
		if(s != null) {
			try {
				r = URLEncoder.encode(s, "utf-8");
			} catch(Exception e) {
				e.printStackTrace();
				//do nothing
			}
		}
		return r;
	}
	
	public static String toUtf8Decode(String s) {
		String r = null;
		if(s != null) {
			try {
				r = URLDecoder.decode(s, "utf-8");
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		return r;
	}
	
	public static String md5(String toMd5) throws UnsupportedEncodingException{
		if(!StringUtils.isNotEmpty(toMd5)) {
			throw new NullArgumentException("加密参数为null");
		}
		return toString(md5Private(toMd5.getBytes())).toUpperCase();
	}
	
	/**
	 * 进行md5运算
	 * @param cs
	 * @return
	 */
	private static byte[] md5Private(byte[] cs) {
		byte[] rs = null;
	      try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			rs = md.digest(cs);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} 
		return rs;
	}
	
	public static String toString(byte[] a) {
        if (a == null)
            return "null";
        if (a.length == 0)
            return "";
 
        StringBuilder buf = new StringBuilder();
 
        for (int i = 0; i < a.length; i++) {
        	if (a[i] < 0)
        		buf.append(Integer.toHexString(a[i]&0xff));
        	else if (a[i] < 16) {
        		buf.append('0');
        		buf.append(Integer.toHexString(a[i]));
        	} else {
        		buf.append(Integer.toHexString(a[i]));
        	}
        }
 
        return buf.toString();
    }
}
